#include "bookmarkbar.h"
#include <QMenu>
#include <QDebug>

BookmarkBar::BookmarkBar(QWidget *parent) :
	QWidget(parent),
	tempItem(new BookmarkItem()),
	toolBar(new QToolBar(this))
{
	connect(toolBar, SIGNAL(actionTriggered(QAction*)), this, SLOT(openBookmark(QAction*)));
}

void BookmarkBar::showBookmarks(QVector<BookmarkItem *> *bookmarks)
{
	QMenu *menu;
	QAction *action_one, *action_two;
	BookmarkItem *item_one, *item_two;
	for(int i = 0; i < bookmarks->size(); i++) {
		item_one = bookmarks->at(i);
		if(item_one->isFolder()) {
			menu = new QMenu(item_one->title(), this);
			action_one = toolBar->addAction(item_one->icon(),item_one->title());
			for(int i = 0; i <  item_one->contain()->size(); i++) {
				item_two = item_one->contain()->at(i);
				action_two = menu->addAction(item_two->icon(), item_two->title());
				action_two->setData(item_two->url());
			}
			action_one->setMenu(menu);
		} else {
			action_one = toolBar->addAction(item_one->icon(), item_one->title());
			action_one->setData(item_one->url());
		}
	}
	bookmarks->clear();
}
void BookmarkBar::openBookmark(QAction *action)
{
	if(action->menu()) {
		QAction *selectedBookmark = action->menu()->exec(QPoint(QCursor::pos().x() - 20, toolBar->mapToGlobal(QPoint(0, 0)).y() + toolBar->height()));
		if(!selectedBookmark)
			return;
		tempItem->change(selectedBookmark->data().toString(), selectedBookmark->text(), selectedBookmark->icon());
	} else
		tempItem->change(action->data().toString(), action->text(), action->icon());
	emit bookmarkOpened(tempItem, Qt::LeftButton);
}
